package cn.edu.sxw.web.server.utils;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 密码加密工具类
 */
public class PasswordEncoder {
    private final static char[] HEX="0123456789abcdef".toCharArray();

    /**
     * 文本md5加密
     * @param text
     * @return
     */
    public static String encode(String text){
        try{
            MessageDigest md5=MessageDigest.getInstance("MD5");
            md5.update(text.getBytes());
            return bytes2Hex(md5.digest());
        }catch (NoSuchAlgorithmException e){
            e.printStackTrace();
        }
        return null;
    }

    private static String bytes2Hex(byte [] bytes){
        char[] chs=new char[bytes.length*2];
        for(int i=0,offset=0;i<bytes.length;i++){
            chs[offset++]=HEX[bytes[i]>>4&0xf];
            chs[offset++]=HEX[bytes[i]&0xf];
        }
        return new String(chs);
    }

    /**
     * 工具类main方法运算出加密密文，填入数据库
     * @param args
     */
    public static void main(String [] args){
        System.out.println(PasswordEncoder.encode("admin123"));
    }
}
